package com.store.app.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.Result;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.IDUtil;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;
import com.store.app.zxing.Capture_ZxingActivity;

import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 支付宝扫码收款
 */

public class AlipayCaptureActivity extends Capture_ZxingActivity implements IOnHttpListener{
    private TextView title_tv;
	private String money = "0.0";
	private TextView tv_cap,tv_cap_money;
	private NetRequest netRequest;

	private String out_trade_no;
	private String transaction_no;
	private  int times = 0;
	Timer timer;
	private boolean ifQuery = false;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1) {
				setReCapture();
			}
		}
	};
	@Override
	public void onAfinalFail() {
		handler.sendEmptyMessageDelayed(1, 5000);
		ToastUtils.showTextToast(AlipayCaptureActivity.this, "请检查本地网络");
		dismissProgressDialog();
	}

	@Override
	public void onExecuteSuccess(int requestId, String result, String msg) {
		if(requestId == 1){
			try {
				JSONObject jsonObject = new JSONObject(result);
				transaction_no = jsonObject.getString("transaction_no");
				Log.v("zyl", "transaction_no:" + transaction_no);
				timer = new Timer();
				TimerTask task = new TimerTask() {
					public void run() {
						//每次需要执行的代码放到这里面。
						if(times > 8){
							Log.v("zyl", "达到9次 取消");
							times = 0;
							timer.cancel();
							dismissProgressDialog();
						}else{
							times++;
							queryState();
						}
					}
				};
				timer.schedule(task, 0, 5000);
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		//确定交易状态成功
		else if(requestId == 2){
			ifQuery = false;
			try {
				JSONObject jsonObject = new JSONObject(result);
				String transaction_status = jsonObject.getString("transaction_status");
				Log.v("zyl","支付状态未："+transaction_status);
				if(transaction_status.equals("completed")){
					dismissProgressDialog();
					timer.cancel();
					times = 0;
					Intent intent = new Intent();
					intent.putExtra("resultMoney",money);
					intent.putExtra("transaction_no",transaction_no);
					intent.putExtra("out_trade_no",out_trade_no);
					setResult(Activity.RESULT_OK, intent);
					finish();
				}else if(transaction_status.equals("closed")){
					handler.sendEmptyMessageDelayed(1, 0);
					dismissProgressDialog();
					timer.cancel();
					times = 0;
					showToast("交易已取消，请重新扫描对方付款码！");
				}else{

				}
			}catch (Exception e){}
		}
	}

	@Override
	public void onExecuteFail(int requestId, String msg) {
		handler.sendEmptyMessageDelayed(1, 5000);
		if(requestId != 2){
			dismissProgressDialog();
			ToastUtils.showTextToast(AlipayCaptureActivity.this, msg);
		}else{
			ifQuery = false;
		}
	}

	/**
	 * 查询交易状态
	 */
	public void queryState(){
		Log.v("zyl", "当前是否在轮询中:" + ifQuery);
		//如果在查询中，则不查询
		if(!ifQuery){
			ifQuery = true;
			Log.v("zyl","第"+times+"次轮询");
			netRequest.requestTransactionStatusFind(2,transaction_no);
		}else{
			Log.v("zyl","跳过此次轮询");
		}
	}


	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		netRequest = new NetRequest(this);
		ExitApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_wechat_capture);
		getWindow()
				.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		money=getIntent().getStringExtra("money");
		Log.v("zyl", "AlipayCaptureActivity:" + money);
		setInintView();
		findViewById();
	}



	private void findViewById() {
		findViewById(R.id.retreat).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		title_tv= (TextView) findViewById(R.id.title_tv);
		tv_cap_money= (TextView) findViewById(R.id.cap_tv_money);
		title_tv.setText("支付宝收款");
		tv_cap= (TextView) findViewById(R.id.cap_tv);
		int width = LocationApplication.app.getDM().widthPixels;
		int high=LocationApplication.app.getDM().heightPixels;
		width=width/8*3;
		high=high/2+width;
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		layoutParams.topMargin=high + MainActivity.dip2px(20);
		layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
		tv_cap.setLayoutParams(layoutParams);
		tv_cap.setText("扫描买方支付宝付款码，即可支付宝支付");
		tv_cap_money.setText(money);
	}
	/**
	 * 处理扫描结果
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = result.getText();

			if (!TextUtils.isEmpty(resultString)&& Utils.isNumber(resultString)) {
				showProgressDialog("支付宝收款", "收款中……");
				out_trade_no = IDUtil.getOutTradeNo();
				netRequest.requestAlipay(1,resultString,money+"",out_trade_no);
			}else{
				ToastUtils.showTextToast(AlipayCaptureActivity.this,"无法识别此二维码");
				handler.sendEmptyMessageDelayed(1,5000);
			}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		handler.removeCallbacksAndMessages(null);
	}
}
